use axum::Json;
use serde_json::Value;
use crate::{ file, utils::{host, timer} };

use super::utils::exist;

pub async fn create_folder() -> Result<&'static str, Json<Value>>{
    let path = "upload/download/temp";
    file::create::create_dir_all_rel(path).await?;
    Ok(path)
}

pub async fn base64(b64:Option<String>, name:&str, suffix:&str) -> Result<String, Json<Value>>{
    let path = create_folder().await?;
    let path = format!("./{}/{}.{}", path, name, suffix);
    
    let buffer = crate::base64::decode(b64)?;
    
    if !exist(&path)? {
        _ = file::create::create_file_write_all_bytes(&path, &buffer).await?;
    }

    // 
    tokio::spawn(async move{
        timer::set_timeout_async(5, async move{
            _ = file::remove::remove_file(&path).await;
        }).await
    });

    let url = format!("{}{}.{}", host::download_temp_url(), name, suffix);
    
    Ok(url)
}